package com.eden.web.controller.school;

import com.eden.common.annotation.Log;
import com.eden.common.constant.UserConstants;
import com.eden.common.core.controller.BaseController;
import com.eden.common.core.domain.AjaxResult;
import com.eden.common.core.page.TableDataInfo;
import com.eden.common.enums.BusinessType;
import com.eden.common.utils.poi.ExcelUtil;
import com.eden.framework.shiro.service.SysPasswordService;
import com.eden.framework.util.ShiroUtils;
import com.eden.school.domain.SchoolUser;
import com.eden.school.service.ISchoolUserService;
import com.eden.system.domain.SysRole;
import com.eden.system.service.ISysPostService;
import com.eden.system.service.ISysRoleService;
import com.eden.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 学校用户信息Controller
 *
 * @author jiaoyang
 * @date 2020-09-01
 */
@Controller
@RequestMapping("/school/schoolUser")
public class SchoolUserController extends BaseController {
    private String prefix = "school/schoolUser";

    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISchoolUserService schoolUserService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysUserService sysUserService;

    @RequiresPermissions("school:schoolUser:view")
    @GetMapping()
    public String schoolUser() {
        return prefix + "/schoolUser";
    }

    /**
     * 查询学校用户信息列表
     */
    @RequiresPermissions("school:schoolUser:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SchoolUser schoolUser) {
        startPage();
        List<SchoolUser> list = schoolUserService.selectSchoolUserList(schoolUser);
        return getDataTable(list);
    }

    /**
     * 导出学校用户信息列表
     */
    @RequiresPermissions("school:schoolUser:export")
    @Log(title = "学校用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SchoolUser schoolUser) {
        List<SchoolUser> list = schoolUserService.selectSchoolUserList(schoolUser);
        ExcelUtil<SchoolUser> util = new ExcelUtil<SchoolUser>(SchoolUser.class);
        return util.exportExcel(list, "schoolUser");
    }

    /**
     * 新增学校用户信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin() && r.getRoleId() != 2 && r.getRoleId() != 3).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存学校用户信息
     */
    @RequiresPermissions("school:schoolUser:add")
    @Log(title = "学校用户信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SchoolUser schoolUser) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(schoolUserService.checkSchoolLoginNameUnique(schoolUser.getLoginName()))) {
            return error("新增用户'" + schoolUser.getLoginName() + "'失败，登录账号已存在");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(schoolUserService.checkSchoolPhoneUnique(schoolUser))) {
            return error("新增用户'" + schoolUser.getLoginName() + "'失败，手机号码已存在");
        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(schoolUserService.checkSchoolEmailUnique(schoolUser))) {
            return error("新增用户'" + schoolUser.getLoginName() + "'失败，邮箱账号已存在");
        }
        schoolUser.setSalt(ShiroUtils.randomSalt());
        schoolUser.setPassword(passwordService.encryptPassword(schoolUser.getLoginName(), schoolUser.getPassword(), schoolUser.getSalt()));
        schoolUser.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(schoolUserService.insertSchoolUser(schoolUser));
    }

    /**
     * 修改学校用户信息
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        SchoolUser schoolUser = schoolUserService.selectSchoolUserById(userId);
        List<SysRole> sysRoles = roleService.selectRoleAll().stream().filter(r -> !r.isAdmin() && r.getRoleId() != 2 && r.getRoleId() != 3).collect(Collectors.toList());
        sysRoles.forEach(role -> {
            if (role.getRoleId().equals(schoolUser.getRoleId())) {
                role.setFlag(true);
            }
        });
        mmap.put("roles", sysRoles);
        mmap.put("schoolUser", schoolUser);
        return prefix + "/edit";
    }

    /**
     * 修改保存学校用户信息
     */
    @RequiresPermissions("school:schoolUser:edit")
    @Log(title = "学校用户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SchoolUser schoolUser) {
        return toAjax(schoolUserService.updateSchoolUser(schoolUser));
    }

    /**
     * 删除学校用户信息
     */
    @RequiresPermissions("school:schoolUser:remove")
    @Log(title = "学校用户信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(schoolUserService.deleteSchoolUserByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkSchoolLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SchoolUser schoolUser) {
        return schoolUserService.checkSchoolLoginNameUnique(schoolUser.getLoginName());
    }

    /**
     * 检查老密码
     *
     * @param password
     * @return
     */
    @GetMapping("/checkPassword")
    @ResponseBody
    public boolean checkPassword(String password, Long userId) {
        SchoolUser schoolUser = schoolUserService.selectSchoolUserById(userId);
        if (passwordService.matches(schoolUser, password)) {
            return true;
        }
        return false;
    }

    /**
     * 修改密码
     *
     * @param userId
     * @param mmap
     * @return
     */
    @RequiresPermissions("school:schoolUser:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", schoolUserService.selectSchoolUserById(userId));
        return prefix + "/profile/resetPwd";
    }

    @RequiresPermissions("school:schoolUser:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SchoolUser user) {
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (schoolUserService.resetSchoolUserPwd(user) > 0) {
            return success();
        }
        return error();
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkSchoolPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SchoolUser schoolUser) {
        return schoolUserService.checkSchoolPhoneUnique(schoolUser);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkSchoolEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SchoolUser schoolUser) {
        return schoolUserService.checkSchoolEmailUnique(schoolUser);
    }

}
